package model

import (
	"fmt"
	"go-devops/common"
	"log"
	"net/http"
	"sync"
)

type SseEvent struct {
	id   string      `json:"id"`
	Data interface{} `json:"data"`
}

type SseStream struct {
	Writer http.ResponseWriter
	Mutex  sync.RWMutex
	Id     string
}

func (s *SseStream) Send(event SseEvent) error {
	s.Mutex.Lock()
	event.id = s.Id
	log.Printf("sse send event:%s\n", common.JsonString(event))
	message := fmt.Sprintf("id: %s\ndata: %s\n\n", event.id, common.JsonBytes(event.Data))
	_, err := s.Writer.Write([]byte(message))
	if err != nil {
		return err
	}
	s.Writer.(http.Flusher).Flush()
	s.Writer.WriteHeader(http.StatusOK)
	s.Mutex.Unlock()
	return nil
}
